package com.components.base.view

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextSwitcher
import android.widget.TextView
import android.widget.ViewSwitcher
import com.components.base.R

class CustomTextSwitcher(context: Context, attrs: AttributeSet?) : TextSwitcher(context, attrs),
    ViewSwitcher.ViewFactory {

    /**数据源*/
    private var mData: MutableList<String> = mutableListOf()

    /**轮循时间*/
    private var mTimeInterval: Long = 1000L

    /**当前数据下标*/
    private var mCurrentIndex = 0

    /**当前点击文本下标*/
    private var currentTextPosition = -1

    private var mOnItemClickListener: OnItemClickListener? = null

    init {
        setFactory(this)
    }

    fun setInAnimation(animationResId: Int): CustomTextSwitcher {
        val animation = AnimationUtils.loadAnimation(context, animationResId)
        inAnimation = animation
        return this
    }

    fun setOutAnimation(animationResId: Int): CustomTextSwitcher {
        val animation = AnimationUtils.loadAnimation(context, animationResId)
        outAnimation = animation
        return this
    }

    /**绑定数据*/
    fun bindData(data: MutableList<String>): CustomTextSwitcher {
        mData = data
        return this
    }

    fun startSwitch(time: Long) {
        this.mTimeInterval = time
        if (mData.size > 0) {
            mSwitchHandler.sendEmptyMessage(0)
        } else {
            throw RuntimeException("data is Empty")
        }
    }

    override fun makeView(): View {
        val textView = TextView(context)
        textView.setSingleLine()
        textView.ellipsize = TextUtils.TruncateAt.MARQUEE
        textView.isFocusable = true
        textView.isClickable = true
        textView.setOnClickListener {
            mOnItemClickListener?.onItemClick(it, currentTextPosition)
        }

//        val textView = MarqueeView(context)
//        textView.text = "这是必须的嘛？？？"
//        textView.textSize = 16F
        return textView
    }

    private var mSwitchHandler = @SuppressLint("HandlerLeak")
    object : Handler(Looper.myLooper() ?: Looper.getMainLooper()) {
        override fun dispatchMessage(msg: Message) {
            super.dispatchMessage(msg)
            currentTextPosition = mCurrentIndex % mData.size
            mCurrentIndex++
            setText(mData[currentTextPosition])
            sendEmptyMessageDelayed(0, mTimeInterval)
        }
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener): CustomTextSwitcher {
        mOnItemClickListener = onItemClickListener
        return this
    }

}